package com.xiaoxing.paimai.mvp.ui.activity;

import android.Manifest;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.google.gson.Gson;
import com.jess.arms.base.BaseActivity;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.ArmsUtils;
import com.jess.arms.utils.LogUtils;
import com.xiaoxing.gifloadingview.LoadingDialogUtil;
import com.xiaoxing.paimai.R;
import com.xiaoxing.paimai.di.component.DaggerLoginComponent;
import com.xiaoxing.paimai.di.module.LoginModule;
import com.xiaoxing.paimai.mvp.contract.LoginContract;
import com.xiaoxing.paimai.mvp.presenter.LoginPresenter;
import com.xiaoxing.paimai.mvp.ui.entity.Login;
import com.xiaoxing.paimai.mvp.ui.entity.UserInfo;
import com.xw.repo.XEditText;

import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;

import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import me.jessyan.armscomponent.commonres.utils.ToolbarUtils;
import me.jessyan.armscomponent.commonsdk.core.BaseConstants;
import me.jessyan.armscomponent.commonsdk.core.RouterHub;
import me.jessyan.armscomponent.commonsdk.utils.ManifestUtil;
import me.jessyan.armscomponent.commonsdk.utils.NetworkUtil;
import me.jessyan.armscomponent.commonsdk.utils.Utils;
import pub.devrel.easypermissions.EasyPermissions;

import static com.jess.arms.utils.Preconditions.checkNotNull;


@Route(path = RouterHub.APP_LOGIN_ACTIVITY)
public class LoginActivity extends BaseActivity<LoginPresenter> implements LoginContract.View, EasyPermissions.PermissionCallbacks {

    private static final int LOGIN_SUCCESS = 0;
    private static final int USER_PASSWORD_ERRO = 1;
    private static final int NETWORK_ERROR = 2;
    private static final int SYS_ERROR = 3;
    @BindView(R.id.xet_username)
    XEditText xetUsername;
    @BindView(R.id.xet_password)
    XEditText xetPassword;
    @BindView(R.id.cb_ji_zhu_mi_ma)
    CheckBox cbJiZhuMiMa;
    @BindView(R.id.btn_login)
    Button btnLogin;
    @BindView(R.id.btn_she_zhi)
    Button btnSheZhi;
    private MyHandler mMyHandler;
    private String[] permissions = {Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION};

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);

        if (requestCode == 104) {

        }
    }

    @Override
    public void onPermissionsGranted(int requestCode, @NonNull List<String> perms) {
        ArmsUtils.makeText(this, "相关权限获取成功");
    }

    @Override
    public void onPermissionsDenied(int requestCode, @NonNull List<String> perms) {
        ArmsUtils.makeText(this, "请同意相关权限，否则功能无法使用");
    }

    @Override
    public void setupActivityComponent(@NonNull AppComponent appComponent) {
        DaggerLoginComponent //如找不到该类,请编译一下项目
                .builder()
                .appComponent(appComponent)
                .loginModule(new LoginModule(this))
                .build()
                .inject(this);
    }

    @Override
    public int initView(@Nullable Bundle savedInstanceState) {
        return R.layout.activity_login; //如果你不需要框架帮你设置 setContentView(id) 需要自行设置,请返回 0
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {

        if (TextUtils.isEmpty(mSharedPreferencesHelper.getString(BaseConstants.SHE_ZHI_IP)) && TextUtils.isEmpty(mSharedPreferencesHelper.getString(BaseConstants.SHE_ZHI_PORT))) {
            mSharedPreferencesHelper.putString(BaseConstants.SHE_ZHI_IP, "dzaudit.xywuhe.com");
            mSharedPreferencesHelper.putString(BaseConstants.SHE_ZHI_PORT, "80");
        }


        ToolbarUtils.initToolbarTitleNoBack(this, getString(R.string.login_deng_lu));
        mMyHandler = new MyHandler();
        if (mSharedPreferencesHelper.getBoolean(BaseConstants.JI_ZHU_MI_MA)) {
            cbJiZhuMiMa.setChecked(true);
        }

        autoLogin();
    }

    /**
     * 自动登陆
     */
    public void autoLogin() {
        if (NetworkUtil.checkNetworkAvailable(this)) {

            String username = mSharedPreferencesHelper.getString(BaseConstants.USERNAME);
            String pwd = mSharedPreferencesHelper.getString(BaseConstants.PASSWORD);
            if (username != null && pwd != null) {
                xetUsername.setText(username);
                if (jiZhuMiMaIsChecked()) {
                    xetPassword.setText(pwd);
//                    login();
                }

            }
        }
    }

    private boolean jiZhuMiMaIsChecked() {
        return cbJiZhuMiMa.isChecked();
    }

    @Override
    public void showLoading() {

        LoadingDialogUtil.showGifdialog1(getSupportFragmentManager(), R.drawable.loading);
    }

    @Override
    public void hideLoading() {
        LoadingDialogUtil.dismissDialog();
    }

    @Override
    public void showMessage(@NonNull String message) {
        checkNotNull(message);
        ArmsUtils.snackbarText(message);
    }

    @Override
    public void launchActivity(@NonNull Intent intent) {
        checkNotNull(intent);
        ArmsUtils.startActivity(intent);
    }

    @Override
    public void killMyself() {
        finish();
    }

    @OnClick({R.id.cb_ji_zhu_mi_ma, R.id.btn_login, R.id.btn_she_zhi})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.cb_ji_zhu_mi_ma:
                jiZhuMiMa();
                break;
            case R.id.btn_login:
                if (getPermission())
                    login();
                break;
            case R.id.btn_she_zhi:
                toSheZhiActivity();
                break;
        }
    }

    /**
     * 点击记住密码Checkbox
     */
    private void jiZhuMiMa() {
        if (jiZhuMiMaIsChecked()) {
            mSharedPreferencesHelper.putBoolean(BaseConstants.JI_ZHU_MI_MA, true);
        } else {
            mSharedPreferencesHelper.putBoolean(BaseConstants.JI_ZHU_MI_MA, false);
        }
    }

    private boolean getPermission() {
        if (EasyPermissions.hasPermissions(this, permissions)) {
            return true;
        } else {
//            EasyPermissions.requestPermissions(this, "需要获取您的相册、照相使用权限", 1, permissions);
            EasyPermissions.requestPermissions(this, "需要获取您的使用权限", 1, permissions);
            return false;
        }

    }

    /**
     * 点击登录
     */
    private void login() {
        String sheZhiIP = mSharedPreferencesHelper.getString(BaseConstants.SHE_ZHI_IP);
        String sheZhiPORT = mSharedPreferencesHelper.getString(BaseConstants.SHE_ZHI_PORT);

        if (TextUtils.isEmpty(sheZhiIP) || TextUtils.isEmpty(sheZhiPORT)) {
            ArmsUtils.snackbarText(getString(R.string.qing_xian_she_zhi_ip_port));
            toSheZhiActivity();
            return;
        }

        if (TextUtils.isEmpty(getUsername())) {
            ArmsUtils.snackbarText(getString(R.string.zhang_hao_bu_neng_wei_kong));
            return;
        }

        if (TextUtils.isEmpty(getPassword())) {
            ArmsUtils.snackbarText(getString(R.string.mi_ma_bu_neng_wei_kong));
            return;
        }

        mSharedPreferencesHelper.putString(BaseConstants.USERNAME, getUsername());
        if (jiZhuMiMaIsChecked()) {
            mSharedPreferencesHelper.putBoolean(BaseConstants.JI_ZHU_MI_MA, true);
            mSharedPreferencesHelper.putString(BaseConstants.PASSWORD, getPassword());
        }
        if (NetworkUtil.checkNetworkAvailable(this)) {

//            mPresenter.login(getUsername(), getPassword());

            new Thread(new Runnable() {
                public void run() {

                    try {

                        int result = callWebService();

                        if (result == LOGIN_SUCCESS) {// 登录成功
                            Message m = new Message();
                            m.what = LoginActivity.LOGIN_SUCCESS;
                            mMyHandler.sendMessage(m);
                        } else if (result == USER_PASSWORD_ERRO) {// 用户名密码错误
                            Message m = new Message();
                            m.what = LoginActivity.USER_PASSWORD_ERRO;
                            mMyHandler.sendMessage(m);
                        }

                    } catch (Exception e) {
                        // SYSException = e.toString();
                        Message m = new Message();
                        m.what = LoginActivity.SYS_ERROR;
                        mMyHandler.sendMessage(m);
                    }
                }
            }).start();
        }
    }

    /**
     * 跳转到设置页面
     */
    private void toSheZhiActivity() {
        Utils.navigation(LoginActivity.this, RouterHub.APP_SHE_ZHI_ACTIVITY);
    }

    @NonNull
    private String getUsername() {
        return xetUsername.getText().toString();
    }

    @NonNull
    private String getPassword() {
        return xetPassword.getText().toString();
    }

    private int callWebService() {
        LoadingDialogUtil.showGifdialog1(getSupportFragmentManager(), R.drawable.loading);

        int result = 0;

        try {

            /****************** 调用webService ***********************/
            // 调用.net 的WebService.
            String nameSpace = "http://tempuri.org/";
            String methodName = "GetUserInfo";

            String url = "http://" + getSpIP() + ":"
                    + getSpPort()
                    + "/ws/ContainerService.asmx";

            LogUtils.debugInfo("url=" + url);
            String soapAction = nameSpace + methodName;

            // 设置连接参数
            SoapObject request = new SoapObject(nameSpace, methodName);

            // 增加属性参数。 将相关的函数参数放入到过程中。
            request.addProperty("user_login", getUsername());
            request.addProperty("user_pass", getPassword());

            SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
                    SoapEnvelope.VER11);// soap协议版本必须用SoapEnvelope.VER11（Soap
            // V1.1）;

            // 注意：这个属性是对dotnetwebservice协议的支持,如果dotnet的webservice
            // 不指定rpc方式则用true否则要用false
            envelope.dotNet = true;

            // envelope.setOutputSoapObject(request);//设置请求参数
            envelope.bodyOut = request; // enveloper.bodyOut=request 与
            // envelope.setOutputSoapObject(request)
            // 效果相同。
            // step4 创建HttpTransportSE对象
            HttpTransportSE ht = new HttpTransportSE(url);
            // step5 调用WebService
            ht.call(soapAction, envelope); // 关键的一步，很多问题都在这一步调试时出现问题。要么是IIS有问题，要么是ksoap2相关参数没配置好。
            if (envelope.getResponse() != null) {
                LoadingDialogUtil.dismissDialog();
                SoapPrimitive response = (SoapPrimitive) envelope.getResponse();
                // if ("1".equals(response.toString())) {
                String t = response.toString();
                LogUtils.debugInfo("t=" + t);

                if (!t.equals("[]")) {

                    t = ArmsUtils.cutLastString(t.substring(1, t.length()));
                    Gson gson = new Gson();
                    UserInfo user = gson.fromJson(t, UserInfo.class);

                    if (user != null) {
                        result = LOGIN_SUCCESS;
                        mSharedPreferencesHelper.putString(BaseConstants.UID, String.valueOf(user.getUserID()));
                    }

                } else {
                    result = USER_PASSWORD_ERRO;
                }

            } else {
                LoadingDialogUtil.dismissDialog();

                result = -1;
            }
            /****************** 调用webService结束 ***********************/

        } catch (Exception e) {
//            SYSException = e.toString();
            LoadingDialogUtil.dismissDialog();

            result = -1;
        }

        return result;
    }

    private String getSpIP() {
        return mSharedPreferencesHelper.getString(BaseConstants.SHE_ZHI_IP);
    }

    private String getSpPort() {
        return mSharedPreferencesHelper.getString(BaseConstants.SHE_ZHI_PORT);
    }

    @Override
    public void loginSuccessed(Login login) {

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mMyHandler != null) {
            mMyHandler = null;
        }
    }

    class MyHandler extends Handler {
        public MyHandler() {
        }

        public MyHandler(Looper L) {
            super(L);
        }

        // 子类必须重写此方法，接受数据
        @Override
        public void handleMessage(Message msg) {
            LoadingDialogUtil.dismissDialog();
            switch (msg.what) {
                case LOGIN_SUCCESS:
                    ArmsUtils.snackbarText("登录成功");

                    String channel = ManifestUtil.getMetaDataFromAppication(LoginActivity.this, "UMENG_CHANNEL");
                    if (channel.equals("chongdiangui")) {//能量e+
                        Utils.navigation(LoginActivity.this, RouterHub.APP_MAIN_ACTIVITY);
                    } else if (channel.equals("cunqugui")) {//自助存取柜
                        Utils.navigation(LoginActivity.this, RouterHub.APP_ZI_ZHU_CUN_QU_GUI_ACTIVITY);
                    }
                    killMyself();

                    break;
                case USER_PASSWORD_ERRO:
                    ArmsUtils.snackbarText(getString(R.string.zhang_hao_huo_mi_ma_cuo_wu));
                    break;
                case NETWORK_ERROR:
                    break;
                case SYS_ERROR:
                    break;
                default:
                    break;
            }


        }
    }
}
